package com.appheader.rongmaphone.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import com.appheader.rongmaphone.MainActivity;
import com.appheader.rongmaphone.R;
import com.appheader.rongmaphone.cache.file.ResourceFileManager;
import com.appheader.rongmaphone.constants.GlobalVars;
import com.appheader.rongmaphone.entity.Project;
import com.appheader.rongmaphone.serializable.SerizlizeableMap;
import com.appheader.rongmaphone.views.RoundProgressBar;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class DialogActivity extends Activity implements View.OnClickListener {
    private RoundProgressBar roundProgressBar;
    private Button startAndStop;
    private final static String TAG = "DialogActivity";
    private int Num = 1;
    boolean isSave = false;

    //加了同步函数，实现
    public synchronized void add(final int totle, String uid, String projectId, String picId, String name, boolean ishave) {
        Num++;
        Log.i("AAA", "T" + Thread.currentThread().getName());
        Log.i("AAA", "T" + Num + "---" + totle);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                roundProgressBar.setProgress(Num * 100 / totle);
            }
        });
        if (Num == totle) {
            //存入数据库
            List<Project> projects = DataSupport.findAll(Project.class);
            for (int i = 0; i < projects.size(); i++) {
                String prjectId = projects.get(i).getPrjectId();
                if (prjectId.equals(projectId)){
                    isSave = true;
                    break;
                }else {
                    isSave = false;
                }
            }
            //如果不存在该方案就保存到数据库
            if (!isSave){
                Project project = new Project();
                project.setIsDownLoad("true");
                project.setPrjectId(projectId);
                project.setPicId(picId);
                project.setName(name);
                project.setPageType("phone");
                project.setCreator(uid);
                boolean save = project.save();//存入成功返回true
                Log.e("DialogActivity", "add: " + save);
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //
            Intent intent = new Intent(DialogActivity.this, ContentActivity.class);
            intent.putExtra("uid", uid);
            intent.putExtra("projectId", projectId);
            intent.putExtra("review", "review");
            intent.putExtra("pageType", "phone");
            Log.e("INTENT", "onItemClick: " + projectId);
            startActivity(intent);
            overridePendingTransition(0, 0);//页面切换没有明显动画
            finish();
        }
//        }

    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉title
        super.onCreate(savedInstanceState);
//        getSupportActionBar().hide();
        setContentView(R.layout.activity_dialog);
        startAndStop = (Button) findViewById(R.id.stop_start);
        startAndStop.setOnClickListener(this);
        getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        roundProgressBar = (RoundProgressBar) findViewById(R.id.roundProgress);

        Intent intent = getIntent();
        String uid = intent.getStringExtra("uid");
        String projectId = intent.getStringExtra("projectId");
        String picId = intent.getStringExtra("picId");
        String name = intent.getStringExtra("name");
        String review = intent.getStringExtra("review");
        Bundle bundle = intent.getExtras();
        SerizlizeableMap serializeMap = (SerizlizeableMap) bundle.get("map");
        Map<Integer, String> map = serializeMap.getMap();
        Log.e("MAPSIZE", "onCreate: " + map.size());
        Log.e(TAG, "onCreate: " + uid + "--" + projectId + "--" + picId + "--" + name + "--" + review);
        downLoad(map, uid, projectId, review, picId, name);

    }

    private void downLoad(final Map<Integer, String> map, final String uid, final String projectId, String review, final String picId, final String name) {
        //以文件个数记录进度值
        Log.e("mapsize", "downLoad: " + map.size());
        for (int i = 0; i < map.size(); i++) {
            final String aa = map.get(i);
            final int fileTotalNum = map.size();//文件个数
            Log.e("Stringaa", "onItemClick: " + i + aa);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.e("TAG", "run:+++++ " + aa);
                    final String paths;
                    final String dirPath;
                    int downLoadFileSize = 0;
                    if (aa.contains("http://")) {//说明存在http://请求协议头
                        String urlPath = ResourceFileManager.splitImgUrlPath(aa).substring(
                                ResourceFileManager.splitImgUrlPath(aa).lastIndexOf("/") + 1);
                        Log.e("TAG---", "run: " + urlPath);
                        String dir1 = splitUrl(aa, 3);//
                        String dir2 = splitUrl(aa, 4);
                        String resource = splitUrl(aa, 5);
                        paths = dir1 + "/" + dir2 + "/" + resource + "/" + urlPath;//全路径
                        dirPath = dir1 + "/" + dir2 + "/" + resource;
                    } else {
                        String urlPath = ResourceFileManager.splitImgUrlPath(aa).substring(
                                ResourceFileManager.splitImgUrlPath(aa).lastIndexOf("/") + 1);
                        Log.e("TAG+++", "run: " + urlPath);
//                        dirPath = ResourceFileManager.splitDirPath(aa).substring(ResourceFileManager.splitDirPath(aa).lastIndexOf("/") + 1);
                        String dir1 = splitUrl(aa, 1);//uid
                        //方案
                        String dir2 = splitUrl(aa, 2);
                        //页名
                        String pageId = splitUrl(aa, 3);
                        paths = dir1 + "/" + dir2 + "/" + pageId + "/" + urlPath;
                        dirPath = dir1 + "/" + dir2 + "/" + pageId;
                    }
                    Log.e("TAGpath", "path= ====" + paths);
                    Log.e("TAGdirPath", "dirPath= ---" + dirPath);
                    //
                    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy
                            .Builder().detectDiskReads().detectDiskWrites()
                            .detectNetwork().penaltyLog().build());
                    try {
                        URL url = null;
                        if (aa.contains("http:")) {
                            Log.e(TAG, "run:---- " + aa.indexOf("http:"));
                            url = new URL(aa);
                        } else {
                            Log.e(TAG, "run:++++ " + "http://" + aa);
                            url = new URL("http://" + aa);
                        }
                        try {
                            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                            urlConnection.setConnectTimeout(5000);
                            if (urlConnection.getResponseCode() != 200) {
                                ++Num;
                                throw new RuntimeException("请求url失败");
                            }
                            urlConnection.connect();
                            int totalLen = urlConnection.getContentLength();
                            Log.e("TAG", "run: " + totalLen);
                            String sdcardRoot = Environment.getExternalStorageDirectory().getAbsolutePath()
                                    + File.separator
                                    + GlobalVars.getPackageInfo().packageName
                                    + "/download"
                                    + File.separator;
                            File rootDir = new File(sdcardRoot + dirPath);
                            //创建目录
                            if (!rootDir.exists()) {
                                boolean is = rootDir.mkdirs();
                                Log.e("IS", "onResponse: ---" + is);
                            }
                            //文件全路径
                            String filePath = sdcardRoot + paths;
                            File file = new File(filePath);
                            if (file.exists()) {
                                file.delete();
                            }
                            //保存指定的json文件路径
                            InputStream inputStream = urlConnection.getInputStream();
                            byte[] buf = new byte[1024];
                            int len = 0;
                            Log.e(TAG, "filePath: -------"+filePath);
                            FileOutputStream fos = new FileOutputStream(filePath);
                            while ((len = inputStream.read(buf)) != -1) {
                                downLoadFileSize += len;
                                fos.write(buf, 0, len);
                                if (downLoadFileSize == totalLen) {
                                    Log.e("FINISH", "run: =========" + true);
                                    Log.e(TAG, "run: ==========total======" + totalLen);
                                    add(fileTotalNum, uid, projectId, picId, name, true);
                                }
                                Log.e("RESOURCE", "ImageDownLoad: " + downLoadFileSize);

                                fos.flush();
                            }
                            inputStream.close();
                            fos.close();
                            urlConnection.disconnect();
                        } catch (IOException e) {
                            e.printStackTrace();
                            Log.e(TAG, "run: error=====" + e.getMessage() + "------" + (++Num));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e(TAG, "run: error=====" + e.getMessage() + aa + "Num=" + (++Num));

                    }
                }
            }).start();
        }
    }

    @Override
    public void onClick(View v) {
        stopDownload();
    }

    private void stopDownload() {
        Intent intent = new Intent(DialogActivity.this, MainActivity.class);
        startActivity(intent);
    }

    private String splitUrl(String url, int i) {
        String[] split = url.split("/");
        return split[i];
    }
}
